package com.zmx.doctor.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.doctor.BaseActivity;
import com.zmx.doctor.R;
import com.zmx.doctor.adapter.PulseConditionListAdapter;
import com.zmx.doctor.adapter.SearchArticleAdapter;
import com.zmx.doctor.okhttp.OkHttp3ClientManager;
import com.zmx.doctor.pojo.PulseCondition;
import com.zmx.doctor.pojo.SearchArticle;
import com.zmx.doctor.pojo.TimeQuantum;
import com.zmx.doctor.utils.AllUtil;
import com.zmx.doctor.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class PulseConditionActivity extends BaseActivity implements OnChartGestureListener, OnChartValueSelectedListener {



    @BindView(R.id.image_head)
    CircleImageView imageHead;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.content)
    TextView content;
    @BindView(R.id.text_tips)
    TextView text_tips;
    @BindView(R.id.no_data)
    TextView no_data;
    @BindView(R.id.text_a)
    TextView textA;
    @BindView(R.id.text_b)
    TextView textB;
    @BindView(R.id.text_c)
    TextView textC;

    private String t_name, head, p_id, list_data;

    private LineChart mChart;
    private LineData data;
    private List<TimeQuantum> list_hr;
    SimpleDateFormat sdFormatter = new SimpleDateFormat("HH:mm");
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    private RecyclerView recyclerView;
//    private PulseConditionListAdapter adapter;
//
//    private List<PulseCondition> lists;

    private SearchArticleAdapter adapter;
    private List<SearchArticle> list;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pulse_condition;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);

        list_data = this.getIntent().getStringExtra("data");
        t_name = this.getIntent().getStringExtra("name");
        p_id = this.getIntent().getStringExtra("p_id");
        head = "http://zmx.123xk.cn/static/upload/member/default.png";
        name.setText(t_name);
        Glide.with(mActivity).load(head).into(imageHead);

        mChart = findViewById(R.id.body_temperature);
        mChart.setOnChartGestureListener(this);
        mChart.setOnChartValueSelectedListener(this);
        mChart.setDrawGridBackground(false);
        // 无描述文本
        mChart.getDescription().setEnabled(false);

        // 使能点击
        mChart.setTouchEnabled(true);

        // 使能拖动和缩放
        mChart.setScaleEnabled(true);
        mChart.setDrawGridBackground(true);
        mChart.setHighlightPerDragEnabled(true);
        mChart.setPinchZoom(true);

        // 如果为false，则x，y两个方向可分别缩放
        mChart.setPinchZoom(true);

        Matrix m = new Matrix();
        m.postScale(10.5f, 1f);//两个参数分别是x,y轴的缩放比例。例如：将x轴的数据放大为之前的1.5倍
        mChart.getViewPortHandler().refresh(m, mChart, true);//将图表动画显示之前进行缩放

        recyclerView = findViewById(R.id.review);
        adapter = new SearchArticleAdapter(mActivity);
        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        recyclerView.setAdapter(adapter);
        list = new ArrayList<>();
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                Intent intent = new Intent();
                intent.putExtra("id", list.get(listPosition).getId());
                intent.setClass(mActivity, TitleMessageActivity.class);
                mActivity.startActivity(intent);
            }
        });
        textA.setTextColor(this.getResources().getColor(R.color.there));

        handler.sendEmptyMessage(1);
//        getPulesStatus();

    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    list_hr = new ArrayList<>();

                    try {

                        JSONObject object = new JSONObject(list_data);
                        content.setText(object.getString("answer"));
                        JSONArray tips = object.getJSONArray("tips");
                        StringBuffer buffer = new StringBuffer();
                        for (int j = 0; j < tips.length(); j++) {
                            buffer.append(tips.get(j).toString() + "\n");
                        }
                        text_tips.setText(buffer.toString());


                        if (!object.isNull("list")) {

                            JSONArray array = object.getJSONArray("list");
                            List<String> rd = new ArrayList<>();
                            for (int i = 0; i < array.length(); i++) {

                                rd.add(array.get(i).toString());

                            }

                            if (rd.size() > 0) {

                                data = getData(rd);
                                mChart.setData(data);
                                mChart.animateX(2000);//动画时间

                            }


                            JSONArray answer = object.getJSONArray("article");
                            Gson g = new Gson();
                            for (int j = 0; j < answer.length(); j++) {

                                SearchArticle im = g.fromJson(answer.getJSONObject(j).toString(), SearchArticle.class);
                                list.add(im);

                            }

                            adapter.setListAndNotifyDataSetChanged(list);

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e("发顺丰", "飞洒发" + e.toString());
                    }

//                    try {
//
//                        JSONObject object = new JSONObject(list_data);
//
//                        Gson gson = new Gson();
//                        JSONArray tips = object.getJSONArray("tips");
//                        StringBuffer buffer = new StringBuffer();
//                        for (int j = 0; j < tips.length(); j++) {
//                            buffer.append(tips.get(j).toString() + "\n");
//                        }
//                        text_tips.setText(buffer.toString());
//
//
//                        if (!object.isNull("trcs")) {
//
//
//                        JSONArray array = object.getJSONArray("list");
//                        content.setText(object.getString("answer"));
//
//                        for (int i = 0; i < array.length(); i++) {
//
//                            JSONObject o = array.getJSONObject(i);
//
//                            TimeQuantum tq = new TimeQuantum();
//                            tq.setHr(o.getInt("hr"));
//                            String s = sdFormatter.format(format.parse(o.getString("hrtime")));
//                            tq.setTime(s);
//                            list_hr.add(tq);
//
//                            PulseCondition doctor = gson.fromJson(array.getJSONObject(i).toString(), PulseCondition.class);
//                            lists.add(doctor);
//
//
//                        }
//
//                        data = getData(list_hr);
//                        mChart.setData(data);
//                        mChart.animateX(2000);//动画时间
//
//                        adapter.setListAndNotifyDataSetChanged(lists);
//
//                        }
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    } catch (ParseException e) {
//                        e.printStackTrace();
//                    }

                    break;

                case 2:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());

                        JSONObject data = object.getJSONObject("data");
                        list_data = data.toString();
                        handler.sendEmptyMessage(1);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

            }
        }
    };

    private LineData getData(List<String> tqs) {

        //设置x轴位置
        XAxis xAxis = mChart.getXAxis();

        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);

        xAxis.setEnabled(true);//设置轴启用或禁用 如果禁用以下的设置全部不生效
        xAxis.setDrawAxisLine(true);//是否绘制轴线

        //设置X轴上每个竖线是否显示
        xAxis.setDrawGridLines(true);
        //设置是否绘制X轴上的对应值(标签)
        xAxis.setDrawLabels(true);
        //设置x轴间距
        xAxis.setGranularity(5f);
        xAxis.setLabelCount(tqs.size(), true);
        xAxis.setLabelCount(10);//一个界面显示10个Lable。那么这里要设置11个
        // 横坐标文字
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return "";
//                if (value < tqs.size()){
//
////                    String str = tqs.get((int) value);
////                    Log.e("显示的天数",""+str);
//                    return "";
//
//                }else {
//
//                    return "";
//
//                }
            }
        });

        //去除右边的y轴
        YAxis yAxisRight = mChart.getAxisRight();
        yAxisRight.setEnabled(false);
        ArrayList<Entry> yVals1 = new ArrayList<Entry>();
        for (int i = 0; i < tqs.size(); i++) {
            // 要显示的数据
            yVals1.add(new Entry(i, Float.parseFloat(tqs.get(i) + "")));

        }

        //一条曲线对应一个LineDataSet
        LineDataSet set1 = new LineDataSet(yVals1, "记录值");
        set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);//设置曲线为圆滑的线
        set1.setCubicIntensity(0.2f);
        set1.setValueTextSize(8f);
        set1.setDrawCircles(true);  //设置有圆点
        set1.setLineWidth(0.8f);    //设置线的宽度
        set1.setCircleSize(1f);   //设置小圆的大小

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(set1); // add the datasets
        LineData data = new LineData(dataSets);

        return data;
    }

//    private LineData getData(List<TimeQuantum> tqs) {
//        //设置x轴位置
//        XAxis xAxis = mChart.getXAxis();
//        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
//        //设置X轴上每个竖线是否显示
//        xAxis.setDrawGridLines(true);
//        //设置是否绘制X轴上的对应值(标签)
//        xAxis.setDrawLabels(true);
//        //设置x轴间距
//        xAxis.setGranularity(1f);
////        xAxis.setLabelCount(tqs.size(),true);
//        xAxis.setLabelCount(15);//一个界面显示10个Lable。那么这里要设置11个
//        xAxis.setLabelRotationAngle(-30);
//
//        // 横坐标文字
//        xAxis.setValueFormatter(new IAxisValueFormatter() {
//            @Override
//            public String getFormattedValue(float value, AxisBase axis) {
//
//                if (tqs.size() < 3) {
//                    return "";
//                }
//
//                if (value < tqs.size()) {
//
//                    String str = tqs.get((int) value).getTime();
//
//                    return str;
//
//                } else {
//
//                    return null;
//
//                }
//            }
//        });
//
//        //去除右边的y轴
//        YAxis yAxisRight = mChart.getAxisRight();
//        yAxisRight.setEnabled(false);
//        ArrayList<Entry> yVals1 = new ArrayList<Entry>();
//        for (int i = 0; i < tqs.size(); i++) {
//            // 要显示的数据
//            yVals1.add(new Entry(i, Float.parseFloat(tqs.get(i).getHr() + "")));
//
//        }
//
//        //一条曲线对应一个LineDataSet
//        LineDataSet set1 = new LineDataSet(yVals1, "记录值");
//        set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);//设置曲线为圆滑的线
//        set1.setCubicIntensity(0.2f);
//        set1.setValueTextSize(8f);
//        set1.setDrawCircles(true);  //设置有圆点
//        set1.setLineWidth(0.8f);    //设置线的宽度
//        set1.setCircleSize(1f);   //设置小圆的大小
//
//        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
//        dataSets.add(set1); // add the datasets
//        LineData data = new LineData(dataSets);
//
//        return data;
//    }


    @Override
    public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {

    }

    @Override
    public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {

    }

    @Override
    public void onChartLongPressed(MotionEvent me) {

    }

    @Override
    public void onChartDoubleTapped(MotionEvent me) {

    }

    @Override
    public void onChartSingleTapped(MotionEvent me) {

    }

    @Override
    public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) {

    }

    @Override
    public void onChartScale(MotionEvent me, float scaleX, float scaleY) {

    }

    @Override
    public void onChartTranslate(MotionEvent me, float dX, float dY) {

    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }

//    @OnClick({R.id.text_a, R.id.text_b, R.id.text_c})
//    public void onViewClicked(View view) {
//        switch (view.getId()) {
//            case R.id.text_a:
//
//                getPulesStatus("5");
//                textA.setTextColor(this.getResources().getColor(R.color.there));
//                textB.setTextColor(this.getResources().getColor(R.color.hui));
//                textC.setTextColor(this.getResources().getColor(R.color.hui));
//
//                break;
//            case R.id.text_b:
//
//                getPulesStatus("10");
//                textA.setTextColor(this.getResources().getColor(R.color.hui));
//                textB.setTextColor(this.getResources().getColor(R.color.there));
//                textC.setTextColor(this.getResources().getColor(R.color.hui));
//
//                break;
//            case R.id.text_c:
//
//                getPulesStatus("30");
//                textA.setTextColor(this.getResources().getColor(R.color.hui));
//                textB.setTextColor(this.getResources().getColor(R.color.hui));
//                textC.setTextColor(this.getResources().getColor(R.color.there));
//
//                break;
//        }
//    }


//    /**
//     * 检测脉象
//     */
//    public void getPulesStatus() {
//
//        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/watchApi/ecgshows", null, handler, 1, 404);
//
//    }

//    public void getPulesStatus(String s_time) {
//
//        List<String> ls = new ArrayList<>();
//        ls.add(s_time);
//        ls.add(p_id);
//        //请求网络
//        Map<String, Object> params = new HashMap<String, Object>();
//        params.put("sign", AllUtil.md5(sing(ls)));
//        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
//        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
//        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
//        params.put("cmd", "getPulesStatus");
//        params.put("data[patient_id]", p_id);
//        params.put("data[minute]", s_time);
//        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/watch", params, handler, 2, 404);
//
//    }


}

